#!/usr/bin/env/python3.7
# -*- coding: utf-8 -*-

"""
@File    : record_audio.py
@Time    : 11/30/2021
@Author  : Silence
@Version : 1.0
@Contact : silence2021silence@163.com
@License : (C)Copyright 2021-2021, Silence
@Desc    : None
"""

from __future__ import print_function
import time
import wave
import alsaaudio

class RecordAudio():
    def record_audio(length):
        wav_file = wave.open('./upload_audio/000.wav', 'wb')
        device = 'default'
        inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, channels=2, rate=44100,
                            format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=160, device=device)
        wav_file.setnchannels(2)
        wav_file.setsampwidth(2)
        wav_file.setframerate(44100)
        print('%d channels, %d sampling rate\n' % (wav_file.getnchannels(),
                                                    wav_file.getframerate()))
        inp.setperiodsize(160)
        # 1s = 10000
        loops = length
        while loops > 0:
            loops -= 1
            l, data = inp.read()
            if l:
                wav_file.writeframes(data)
                time.sleep(.001)
        wav_file.close()
        print('record ok')
